#pragma once
#include <iostream>
#include <cstdlib>
#include <vector>
#include <unistd.h>
#include <sys/wait.h>
#include "Task.hpp"

class Channel
{
public:
    Channel(int wfd, pid_t subid) : _wfd(wfd), _subid(subid)
    {
        _name = "channel" + std::to_string(_wfd) + "-" + std::to_string(_subid);
    }

    void Send(int code)
    {
        int n = write(_wfd, &code, sizeof(code));
        (void) n;
    }

    void Close()
    {
        close(_wfd);
    }
    
    void Wait()
    {
        pid_t rid = waitpid(_subid, nullptr, 0);
        (void)rid;
    }

    int Fd() { return _wfd; }
    pid_t SubId() { return _subid; }
    std::string Name() { return _name; }


private:
    int _wfd;
    pid_t _subid;
    std::string _name;
};

class ChannelManager
{
public:
    ChannelManager() : _next(0)
    {}

    void Insert(int wfd, pid_t subid)
    {
        _channels.emplace_back(wfd, subid);
    }

    Channel& Select()
    {
        auto& c = _channels[_next++];

        _next %= _channels.size();
        return c;
    }

    void StopSubProcess()
    {
        for(auto& c : _channels)
        {
            c.Close();
        }
    }

    void WaitSubProcess()
    {
        for(auto& c : _channels)
        {
            c.Wait();
            //sleep(5);
        }
    }

private:
    std::vector<Channel> _channels;
    int _next;
};

class ProcessPool
{
public:
    ProcessPool(int num) : _process_num(num)
    {
        _tm.Register(PrintLog);
        _tm.Register(Download);
        _tm.Register(Upload);
    }

    void Work(int rfd)
    {
        while(1)
        {
            int code = 0;
            ssize_t n = read(rfd, &code, sizeof(code));
            if(n > 0)
            {
                if(n != sizeof(code))
                {
                    //没读取完全的情况就跳过
                    continue;
                }
                std::cout << "Child process[" << getpid() <<"] receive a taskcode: " << code << std::endl;
                _tm.Execte(code);
            }
            else if(n == 0) //读到文件结尾
            {
                std::cout << "Process exit!" << std::endl;
                break;
            }
            else
            {
                std::cout << "Read error!" << std::endl;
                break;
            }
        }
    }
    
    bool Start()
    {
        for(int i = 0; i < _process_num; i++)
        {
            // 1. 创建管道
            int pipefd[2] = {0};
            int n = pipe(pipefd);
            if(n < 0) return false;

            // 2. 创建子进程
            pid_t subid = fork();
            if(subid < 0) return false;
            else if(subid == 0)
            {
                //子进程 -> 读
                //3. 关闭文件描述符
                close(pipefd[1]);   // 子进程需要读取信息，关闭写端
                Work(pipefd[0]);
                close(pipefd[0]);
                //std::cout << "child rfd: " << pipefd[0] << std::endl;
                exit(0);
            }
            else
            {
                // 父进程 -> 写
                //关闭不需要的文件描述符
                close(pipefd[0]);
                _cm.Insert(pipefd[1], subid);
            }
        }
        return true;
    }

    void run()
    {
        //选择任务
        int taskcode = _tm.Code();

        //选择管道->子进程
        auto& c = _cm.Select();
        std::cout << "Select child process: " << c.Name() << std::endl;
        
        //发送任务码
        c.Send(taskcode);
        std::cout << "Send taskcode: " << taskcode << std::endl;
    }

    void Stop()
    {
        //关闭父进程的wfd
        _cm.StopSubProcess();
        // 回收所有子进程
        _cm.WaitSubProcess();

        std::cout << "ProcessPool stop !" << std::endl;
    }

private:
    ChannelManager _cm;
    int _process_num;   //进程的个数
    TaskManager _tm;
};